from django.db import models
from libs.mixins import ModelMixin
from libs.utils import human_time
from django.contrib.auth.hashers import make_password, check_password
import json


class User(models.Model, ModelMixin):
    username = models.CharField(max_length=100, unique=True)  # 登录用户名
    nickname = models.CharField(max_length=100)  # 昵称
    password_hash = models.CharField(max_length=100)  # 加密密码
    is_supper = models.BooleanField(default=False)  # 是否是管理员
    is_active = models.BooleanField(default=True)  # 是否激活状态
    access_token = models.CharField(max_length=32)  # 用于认证的token
    token_expired = models.IntegerField(null=True)  # token的过期时间
    last_login = models.CharField(max_length=20)  # 最后一次登录时间
    role = models.ForeignKey('Role', on_delete=models.PROTECT, null=True)


    created_at = models.CharField(max_length=20, default=human_time)  # 创建时间
    deleted_at = models.CharField(max_length=20, null=True)  # 删除时间
    deleted_by = models.ForeignKey('User', related_name='+', null=True)  # 删除者

    @staticmethod
    def make_password(plain_password: str) -> str:
        return make_password(plain_password, hasher='pbkdf2_sha256')

    def verify_password(self, plain_password: str) -> bool:
        return check_password(plain_password, self.password_hash)

    @property
    def page_perms(self):
        if self.role and self.role.page_perms:
            data = []
            perms = json.loads(self.role.page_perms)
            for m, v in perms.items():
                for p, d in v.items():
                    data.extend(f'{m}.{p}.{x}' for x in d)
            return data
        else:
            return []


    def has_perms(self, codes):
        # return self.is_supper or self.role in codes
        return self.is_supper

    def __repr__(self):
        return '<User %r>' % self.username

    class Meta:
        db_table = 'users'
        ordering = ('-id',)


class Role(models.Model, ModelMixin):
    name = models.CharField(max_length=50)
    desc = models.CharField(max_length=255, null=True)
    page_perms = models.TextField(null=True)

    created_at = models.CharField(max_length=20, default=human_time)
    created_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='+')

    def to_dict(self, *args, **kwargs):
        tmp = super().to_dict(*args, **kwargs)
        tmp['page_perms'] = json.loads(self.page_perms) if self.page_perms else None
        tmp['used'] = self.user_set.count()
        return tmp


    def __repr__(self):
        return '<Role name=%r>' % self.name

    class Meta:
        db_table = 'roles'
        ordering = ('-id',)
